import Taro, {Component, Config} from '@tarojs/taro'
import {
  View,
  Swiper,
  SwiperItem,
  Image,
  Text,
  Button,
  OpenData,
  Ad,
  Input
} from '@tarojs/components'

import {AtTabs, AtTabsPane , AtModal ,  AtModalContent,
  AtModalAction , AtButton} from 'taro-ui'

import './index.scss'

import {base_url} from "../../network/config";

import DataManager from '../../utils/DataManager.js'

import notice_logo from '../../image/ic_notice.png'
import job_logo from '../../image/ic_job.png'
import car_logo from '../../image/ic_find_car.png'
import publish_logo from '../../image/ic_publish.png'
import house_rent_logo from '../../image/ic_house_rent.png'
import shop_rent_logo from '../../image/ic_shop_rent.png'
import sale_logo from '../../image/ic_for_sale.png'
import info_logo from '../../image/ic_info.png'
import life_logo from '../../image/ic_life_service.png'

import JobItem from '../../component/JobItem/jobItem.js'

import emptyIcon from '../../image/ic_empty.png'

import ListEmptyView from '../../component/LiseEmptyView/listEmptyView.js'
import {STORAGE_KEY} from "../../utils/const";

import NewsItem from '../../component/NewsItem/newsItem.js';
import ConvenienceItem from '../../component/ConvenienceItem/convenienceItem'


let newsPage = 1;
let conveniencePage = 1;
let jobPage = 1;

export default class Index extends Component {

  /**
   * 指定config的类型声明为: Taro.Config
   *
   * 由于 typescript 对于 object 类型推导只能推出 Key 的基本类型
   * 对于像 navigationBarTextStyle: 'black' 这样的推导出的类型是 string
   * 提示和声明 navigationBarTextStyle: 'black' | 'white' 类型冲突, 需要显示声明类型
   */
  config = {
    navigationBarTitleText: ''
  }

  constructor(props) {
    super(...arguments)
    this.state = {
      bannerList: [],
      hotNewsList: [],
      jobList: [],
      convenienceList: [],
      tabCurrent: 0,
      hasAuth: false,
      bannerHeight:0,
      areaName:'',
      newsList:[],
      searchKeyword:'',
    }
  }

  componentWillMount() {

    if (!DataManager.getWeiXinId()){
      Taro.redirectTo({
        url:`/pages/index/openAreaList`
      })
      return;
    }

    Taro.showShareMenu({
      withShareTicket: true
    })

    this.setState({
      hasAuth:DataManager.getHasAuth(),
    })

    if (DataManager.getHasAuth()){ // 有授权才直接调用登录  没有授权 获取授权后再登录
      this.login()
    }
  }

  onPullDownRefresh(){
    this.loadBannerList()
    if (this.state.tabCurrent == 0){
      newsPage = 1 ;
      this.loadLatestNews();
    } else if (this.state.tabCurrent == 1){
      conveniencePage = 1;
      this.loadConvenience();
    } else if (this.state.tabCurrent == 2){
      jobPage = 1 ;
      this.loadJob();
    }
  }

  onReachBottom(){
    if (this.state.tabCurrent == 0){
      newsPage ++ ;
      this.loadLatestNews();
    } else if (this.state.tabCurrent == 1){
      conveniencePage ++;
      this.loadConvenience();
    } else if (this.state.tabCurrent == 2){
      jobPage ++ ;
      this.loadJob();
    }
  }

  login(){

    let _this = this;

    Taro.login({
      success(res){
        console.log('weixin login--' + JSON.stringify(res))
        let url = base_url + 'stateless/weixin/weixinAuth'
        Taro.request({
          url:url,
          data: {
            platform:'android_c',
            weixinId:DataManager.getWeiXinId(),
            loginChannel:'wechat',
            appId:'KC876D98B30UA40CJSNHI689FB33SDW',
            digest : 'dda484557c12febe48139d8f44051c13',
            code:res.code
          },
          method: 'GET',
          success(res1) {
            console.log('auth login--' + res1.data.data.openId)
            if (res1.data && res1.data.data && res1.data.data.openId){
              Taro.setStorageSync(STORAGE_KEY.OPEN_ID , res1.data.data.openId);
            }

            let loginParams = {
              platform:'android_c',
              weixinId:DataManager.getWeiXinId(),
              loginChannel:'wechat',
              appId:'KC876D98B30UA40CJSNHI689FB33SDW',
              digest : 'dda484557c12febe48139d8f44051c13',
              username:res1.data.data.openId,
              weixinNickName:DataManager.getWeiXinNickname(),
              weixinHeadImg:DataManager.getWeiXinAvatar()
            }

            if (DataManager.getShareUserId()){
              let inviteParams = {'inviteUserId' : DataManager.getShareUserId()};
              Object.assign(loginParams,inviteParams);
            }

            Taro.request({
              url:base_url + 'login',
              data:loginParams,
              header: { 'content-type': 'application/x-www-form-urlencoded' },
              method: 'POST',
              success(res2) {
                console.log('res2=========]' + JSON.stringify(res2))

                if (res2.data && res2.data.data){
                  if (res2.data.data.token){
                    Taro.setStorageSync(STORAGE_KEY.TOKEN , res2.data.data.token);
                  }
                  Taro.setStorageSync(STORAGE_KEY.IS_BIND_MOBILE , res2.data.data.isBindMobile)
                  Taro.setStorageSync(STORAGE_KEY.IS_BIND_WECHAT , res2.data.data.isBindWechat)
                  Taro.setStorageSync(STORAGE_KEY.MOBILE , res2.data.data.mobile)
                  Taro.setStorageSync(STORAGE_KEY.IS_BUSINESS , res2.data.data.isBusiness)
                  Taro.setStorageSync(STORAGE_KEY.ADDRESS_NAME , res2.data.data.addressName)
                  Taro.setStorageSync(STORAGE_KEY.BUSINESS_MOBILE , res2.data.data.businessMobile)
                  Taro.setStorageSync(STORAGE_KEY.PROXY_MOBILE , res2.data.data.proxyMobile)
                  Taro.setStorageSync(STORAGE_KEY.PROXY_WEIXIN_CODE , res2.data.data.weixinCode)
                  Taro.setStorageSync(STORAGE_KEY.USER_ID , res2.data.data.id)
                }

                //登录成功后请求数据
                newsPage = 1;
                _this.loadLatestNews()
                conveniencePage = 1;
                _this.loadConvenience()
                jobPage = 1;
                _this.loadJob()

                _this.loadBannerList()
                Taro.setNavigationBarTitle({
                  title: DataManager.getAddressName() + '首页'
                })
              }
            })
          }
        })
      }
    })
  }

  componentDidMount() {

    Taro.eventCenter.on('jobPost',() => {
      jobPage = 1;
      this.loadJob();
    })
    Taro.eventCenter.on('shopInfoPost',() => {
      conveniencePage = 1;
      this.loadConvenience();
    })
    Taro.eventCenter.on('areaChange',() => {
      newsPage = 1;
      jobPage = 1;
      conveniencePage = 1;
      this.loadNewsList();
      this.loadBannerList()
    })
  }

  onShareAppMessage(options){
    console.log('      options    ' + JSON.stringify(options));
    let itemShareId = options.target.dataset.itemid
    let itemShareType = options.target.dataset.itemtype;

    let _this = this;

    if (options.from == 'button'){

      let pageUrl;
      if (itemShareType == 1) {
        pageUrl = `/pages/job/jobDetail?jobId=` + itemShareId + `&shareUserId=` + DataManager.getUserId();
      } else if (itemShareType == 2){
        pageUrl = `/pages/car/carDetail?carId=` + itemShareId + `&shareUserId=` + DataManager.getUserId();
      } else if (itemShareType == 3){
        pageUrl = `/pages/shop/shopDetail?shopId=` + itemShareId + `&shareUserId=` + DataManager.getUserId();
      }

      if (itemShareId && itemShareType){
        // 转发成功
        let url = base_url + 'rest/user/share/save';
        Taro.request({
          url:url,
          data: {
            token:DataManager.getToken(),
            platform:'android_c',
            weixinId:DataManager.getWeiXinId(),
            loginChannel:'c',
            appId:'KC876D98B30UA40CJSNHI689FB33SDW',
            digest : 'dda484557c12febe48139d8f44051c13',
            id:itemShareId,
            type:itemShareType,
          },
          header: { 'content-type': 'application/x-www-form-urlencoded' },
          method: 'POST',
          success(res) {
            newsPage = 1;
            jobPage = 1;
            conveniencePage = 1;
            _this.loadNewsList()
          }
        })
      }
      return {
        path: pageUrl,
      }
    }
  }

  componentWillUnmount() {
  }

  componentDidShow() {
    Taro.eventCenter.trigger('tabIndex' ,0);
    if (DataManager.getAreaName()){
      this.setState({
        areaName:DataManager.getAreaName()
      })
    }
  }

  componentDidHide() {
  }

  loadNewsList() {
    this.loadLatestNews()
    this.loadJob()
    this.loadConvenience()
  }

  loadLatestNews(){
    Taro.showLoading({
      title: '拼命加载中...',
      mask: true
    })

    let _this = this;

    let url = base_url + 'stateless/news/newsList'
    Taro.request({
      url: url,
      data: {
        token: DataManager.getToken(),
        platform: 'android_c',
        weixinId: DataManager.getWeiXinId(),
        loginChannel: 'c',
        appId: 'KC876D98B30UA40CJSNHI689FB33SDW',
        digest: 'dda484557c12febe48139d8f44051c13',
        pageNo:newsPage,
        pageSize:20
      },
      method: 'GET',
      success(res) {
        if (!res.data || !res.data.data || !res.data.data.list || res.data.data.list.length < 1){
          if (newsPage > 1){
            newsPage --;
          }
        }

        let news = [];
        if (newsPage == 1){
          news = res.data.data.list
        } else {
          news = _this.state.newsList.concat(res.data.data.list);
        }
        _this.setState({
          newsList: news,
        })
      },
      fail: function () {
        if (newsPage > 1){
          newsPage --;
        }
      },
      complete(){
        Taro.stopPullDownRefresh();
        Taro.hideLoading();
      }
    })
  }

  loadConvenience(){
    let _this = this;

    let url = base_url + 'stateless/category/news/categoryNewsList'
    Taro.request({
      url: url,
      data: {
        token: DataManager.getToken(),
        platform: 'android_c',
        weixinId: DataManager.getWeiXinId(),
        loginChannel: 'c',
        appId: 'KC876D98B30UA40CJSNHI689FB33SDW',
        digest: 'dda484557c12febe48139d8f44051c13',
        pageNo:conveniencePage,
        pageSize:20
      },
      method: 'GET',
      success(res) {

        if (!res.data || !res.data.data || !res.data.data.list || res.data.data.list.length < 1){
          if (conveniencePage > 1){
            conveniencePage --;
          }
        }

        let news = [];
        if (conveniencePage == 1){
          news = res.data.data.list;
        } else {
          news = _this.state.convenienceList.concat(res.data.data.list)
        }


        _this.setState({
          convenienceList: news,
        })
      },
      fail: function () {
        if (conveniencePage > 1){
          conveniencePage --;
        }
      },
      complete(){
        Taro.stopPullDownRefresh();
      }
    })
  }

  loadJob(){
    let _this = this;
    let url = base_url + 'stateless/pin/pinList'
    Taro.request({
      url:url,
      data: {
        token:DataManager.getToken(),
        platform:'android_c',
        weixinId:DataManager.getWeiXinId(),
        loginChannel:'c',
        appId:'KC876D98B30UA40CJSNHI689FB33SDW',
        digest : 'dda484557c12febe48139d8f44051c13',
        pageNo: 1,
        pageSize: 20
      },
      method: 'GET',
      success(res) {

        if (!res.data || !res.data.data || !res.data.data.list || res.data.data.list.length < 1){
          if (jobPage > 1){
            jobPage --;
          }
        }

        let jobs = [];
        if (jobPage == 1){
          jobs = res.data.data.list;
        } else {
          jobs = _this.state.jobList.concat(res.data.data.list)
        }
        _this.setState({
          jobList: jobs,
        })
      },
      fail(){
        if (mPageNum > 1){
          mPageNum --;
        }
      },
      complete(){
        Taro.stopPullDownRefresh();
      }
    })
  }

  loadBannerList() {
    let _this = this;

    let url = base_url + 'stateless/index/indexBannerList'
    Taro.request({
      url: url,
      data: {
        token: DataManager.getToken(),
        platform: 'android_c',
        weixinId: DataManager.getWeiXinId(),
        loginChannel: 'c',
        appId: 'KC876D98B30UA40CJSNHI689FB33SDW',
        digest: 'dda484557c12febe48139d8f44051c13'
      },
      method: 'GET',
      success(res) {
        let banners = [];
        let newsList = [];
        if (res.data.data.bannerList){
          banners = banners.concat(res.data.data.bannerList);
        }
        newsList = res.data.data.castList
        _this.setState({
          bannerList: banners,
          hotNewsList: newsList
        })
      }
    })
  }


  goToJobList = () => {
    Taro.switchTab({url: '/pages/job/jobList'})
  }

  goToCarList = () => {
    Taro.navigateTo({url: '/pages/car/carList'})
  }

  goToConvenienceList = (code) => {
    Taro.navigateTo({url: '/pages/convenience/singleConvenienceList?code=' + code })
  }

  goToPromotion = () => {
    // Taro.navigateTo({url: '/pages/protocol/promotionPage'})
    Taro.getSetting({
      success(res){
        if (!res.authSetting['scope.userLocation']) {
          Taro.authorize({
            scope: 'scope.userLocation',
            success() {

            },
          })
        }
      }
    })
    Taro.getLocation({
      type: 'wgs84',
      success(res) {
        const latitude = res.latitude;
        const longitude = res.longitude;
        console.log('la -- long=====' + latitude + '  ' + longitude )
        Taro.setStorageSync(STORAGE_KEY.LATITUDE , latitude);
        Taro.setStorageSync(STORAGE_KEY.LONGITUDE , longitude);
        Taro.navigateTo({url:'/pages/shop/storeList'})
      }
    });
  }

  handleTabClick (pos) {
    console.log("pos--------------" + JSON.stringify(pos))
    this.setState({
      tabCurrent: pos
    })
  }

  refTabView = (node) => {
    this.tabView = node;
  }

  handleAuth = (e) =>{
    if (e.detail.userInfo){
      Taro.setStorageSync(STORAGE_KEY.HAS_AUTH , true);
      Taro.setStorageSync(STORAGE_KEY.WEIXIN_NICKNAME , e.detail.userInfo.nickName);
      Taro.setStorageSync(STORAGE_KEY.WEIXIN_AVATAR , e.detail.userInfo.avatarUrl);
      this.setState({
        hasAuth:true
      })
      this.login()
    }
  }

  // handleBannerClick = (bannerData) =>{
  //   console.log('banner--click =====' + bannerData.businessType + '    ' + bannerData.businessId)
  //   let businessId = bannerData.businessId;
  //   let bannerUrl = bannerData.bannerUrl;
  //   if (businessId){
  //     if (bannerData.businessType == 2){ // job
  //       Taro.navigateTo({
  //         url: `/pages/job/jobDetail?jobId=` + businessId,
  //       })
  //     } else if (bannerData.businessType == 3){// car
  //       Taro.navigateTo({
  //         url: `/pages/car/carDetail?carId=` + businessId
  //       })
  //     } else if (bannerData.businessType == 4){// shop
  //       Taro.navigateTo({
  //         url: `/pages/shop/shopDetail?shopId=` + businessId
  //       })
  //     }
  //   }
  //
  //   if (bannerUrl && (bannerData.businessType == 0 || bannerData.businessType == 1)){
  //     Taro.navigateTo({
  //       url: `/pages/common/commonWebPage?webUrl=` + bannerUrl + `&webTitle=` + bannerData.title
  //     })
  //   }
  // }

  toChosenArea = () =>{
    Taro.navigateTo({
      url : `/pages/index/openAreaList`
    })
  }

  // bannerLoad = (e) =>{
  //   var winWid = Taro.getSystemInfoSync().windowWidth; //获取当前屏幕的宽度
  //   var winHei = Taro.getSystemInfoSync().windowHeight;
  //   var imgh = e.detail.height;//图片高度
  //   var imgw = e.detail.width;//图片宽度
  //
  //   var swiperH = winWid * imgh / imgw + 'px'
  //   console.log('img------------' + winWid + '    ' + winHei + '       ' + swiperH  )
  //   this.setState({
  //     bannerHeight:30 + 'px'
  //   })
  // }

  handleSearchInput = (e) =>{
    this.setState({
      searchKeyword:e.target.value
    })
  }

  handleSearch = () =>{
    Taro.navigateTo({
      url:'/pages/convenience/singleConvenienceList?keyWord=' + this.state.searchKeyword
    })
  }

  render() {
    // let bannerItem = this.state.bannerList.map(item => {
    //   return <SwiperItem>
    //     <Image
    //       onLoad={this.bannerLoad.bind(this)}
    //       mode='widthFix'
    //       className='banner-item'
    //       src={item.bannerImage}
    //       style='height:{{this.state.bannerHeight}};'
    //       onClick={this.handleBannerClick.bind(this , item)}
    //     />
    //   </SwiperItem>
    // })

    let newsAuto = this.state.hotNewsList.length > 1 ? true : false

    let newsItem = this.state.hotNewsList.map(item => {
      return <SwiperItem>
        <Text className='hot-news-text'>{item.content}</Text>
      </SwiperItem>
    })

    let tabList = [{title: '最新新闻'} , {title: '便民信息'} , {title: '最新招聘'}];

    console.log('areaName===========' + this.state.areaName)

    return (
      <View className='home-page'>
        <View className='home-area-container'>
          <Text className='home-area-name' onClick={this.toChosenArea.bind(this)}>{this.state.areaName}</Text>
          <Input
            className='home-search-input'
            type='text'
            placeholder='请输入关键字'
            cursorSpacing={5}
            onInput={this.handleSearchInput.bind(this)}
          />
          <AtButton
            className='home-search-button'
            type='primary'
            size='small'
            circle
            onClick={this.handleSearch.bind(this)}
          >搜索</AtButton>
        </View>

        {/*{ this.state.bannerList.length > 0 &&*/}
          {/*<Swiper*/}
            {/*circular={this.state.bannerList.length > 1}*/}
            {/*slideMult='10'*/}
            {/*indicatorColor='#999'*/}
            {/*indicatorActiveColor='#333'*/}
            {/*duration={500}*/}
            {/*interval={2000}*/}
            {/*autoplay*/}
            {/*indicatorDots*/}
            {/*className='home-banner'*/}
          {/*>*/}
            {/*{bannerItem}*/}
          {/*</Swiper>*/}
        {/*}*/}
        <View className='home-entrance-container'>
          <View className='home-entrance-item' onClick={this.goToJobList.bind(this)}>
            <Image className='home-entrance-image' src={job_logo}></Image>
            <Text className='home-entrance-text'>招聘</Text>
          </View>
          <View className='home-entrance-item' onClick={this.goToCarList.bind(this)}>
            <Image className='home-entrance-image' src={car_logo}></Image>
            <Text className='home-entrance-text'>找车</Text>
          </View>
          <View className='home-entrance-item' onClick={this.goToConvenienceList.bind(this , 13001)}>
            <Image className='home-entrance-image' src={house_rent_logo}></Image>
            <Text className='home-entrance-text'>房屋租赁</Text>
          </View>
          <View className='home-entrance-item' onClick={this.goToConvenienceList.bind(this , 13002)}>
            <Image className='home-entrance-image' src={shop_rent_logo}></Image>
            <Text className='home-entrance-text'>旺铺租售</Text>
          </View>
        </View>
        <View className='home-entrance-container'>
          <View className='home-entrance-item' onClick={this.goToConvenienceList.bind(this , 13004)}>
            <Image className='home-entrance-image' src={sale_logo}></Image>
            <Text className='home-entrance-text'>优惠促销</Text>
          </View>
          <View className='home-entrance-item' onClick={this.goToConvenienceList.bind(this , 13005)}>
            <Image className='home-entrance-image' src={info_logo}></Image>
            <Text className='home-entrance-text'>咨询打听</Text>
          </View>
          <View className='home-entrance-item' onClick={this.goToConvenienceList.bind(this , 13006)}>
            <Image className='home-entrance-image' src={life_logo}></Image>
            <Text className='home-entrance-text'>生活服务</Text>
          </View>
          <View className='home-entrance-item' onClick={this.goToPromotion.bind(this)}>
            <Image className='home-entrance-image' src={publish_logo}></Image>
            <Text className='home-entrance-text'>114黄页</Text>
          </View>
        </View>
        <View className='home-grey_divider'></View>
        {DataManager.getHasShowAd() &&
          <Ad unitId='adunit-2728963cf10bd0c5' />
        }
        <View className='hot-news-main'>
          <Image className='hot-news-icon' src={notice_logo}></Image>
          <Swiper
            className='hot-news-container'
            indicatorDots={false}
            autoplay={newsAuto}
            interval={2000}
            vertical
            circular
            duration={500}
          >
            {newsItem}
          </Swiper>
        </View>
        <View className='home-grey_divider-thin'></View>
        <View ref={this.refTabView}>
          <AtTabs current={this.state.tabCurrent} tabList={tabList} onClick={this.handleTabClick.bind(this)}  swipeable={false}>
            <AtTabsPane current={this.state.tabCurrent} index={0}>
              {this.state.newsList.length > 0 ? this.state.newsList.map(item => {
                  return <NewsItem newsData={item}></NewsItem>
                })
                :
                <ListEmptyView emptyText='暂无数据' emptyImage={emptyIcon} />
              }
            </AtTabsPane>
            <AtTabsPane current={this.state.tabCurrent} index={1}>
              {this.state.convenienceList.length > 0 ? this.state.convenienceList.map(item => {
                return <ConvenienceItem infoData={item}></ConvenienceItem>
              })
              :
              <ListEmptyView emptyText='暂无数据' emptyImage={emptyIcon} />
              }
            </AtTabsPane>
            <AtTabsPane current={this.state.tabCurrent} index={2} >
              {this.state.jobList.length > 0 ? this.state.jobList.map(item => {
                  return <JobItem jobData={item}></JobItem>
                })
                :
                <ListEmptyView emptyText='暂无数据' emptyImage={emptyIcon} />
              }
            </AtTabsPane>
          </AtTabs>
        </View>
        {!this.state.hasAuth && <AtModal isOpened={!this.state.hasAuth}>
          <AtModalContent>
            <View className='home-auth-container'>
              <OpenData className='home-auth-image' type='userAvatarUrl' />
              <OpenData className='home-auth-name' type='userNickName' />
              <Text style='margin-top:20px;margin-left:20px;margin-right:20px'>
                为了您的正常使用，部分功能需要您授权访问用户信息才可使用
              </Text>
            </View>
          </AtModalContent>
          <AtModalAction>
            <Button open-type='getUserInfo' onGetUserInfo={this.handleAuth.bind(this)}>我知道了</Button>
          </AtModalAction>
        </AtModal>}
      </View>
    )
  }

}

